<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Http\Request;
use App\Transformers\PostTransformer;

class UploadController extends BaseController
{
												
    /**
     * @api {post} /upload/head (create post)
     * @apiDescription 上传用户头像
     * @apiGroup Post
     * @apiPermission jwt
     * @apiParam {String} title  post title
     * @apiParam {String} content  post content
     * @apiVersion 0.1.0
     * @apiSuccessExample {json} Success-Response:
     *   HTTP/1.1 	201 Created
     */
    public function user_head(Request $request)
    {
		\Log::info(\var_export($request->files, true));
		if (!$request->hasFile('headimg')) {
			\Log::error('not hasFile ... ');
			return $this->response->errorBadRequest('not found file');
		}
		$image = $request->image('headimg');
		try{
			$imgurl = $this->save_image($image);
		}catch(\Exception $e){
			$imgurl = false;
			\Log::error('save_image error ... '.$e->getMessage());
		}
		\Log::info('save_image imgurl '.$imgurl);
		if($imgurl){
			$user = $this->user();
			$user->update(['headimg' => $imgurl]);
			return $this->returnSuccess([], '上传成功');
		}
		return $this->response->errorBadRequest('保存失败');
    }

   /**
	* 保存文件
	* 
	*/
	protected function save_image($image, $returl = true, $from = 'user'){
		$user_id = $this->user()->id;
		$name = $user_id.'_'.time().'.'.$image->getClientOriginalExtension();
		$destination_path = storage_path('/app/static/images/'.$from);
		$ret = $image->move($destination_path, $name);
		return $returl ? 'images/'.$from.'/'.$name : $ret;
	}
}
